package org.budo.graph.service.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.budo.graph.Constant;
import org.budo.support.freemarker.FreemarkerUtil;
import org.budo.support.lang.util.MapUtil;
import org.budo.support.spring.io.util.ResourceUtil;
import org.springframework.context.ApplicationContext;

import com.alibaba.druid.stat.DruidStatManagerFacade;
import com.alibaba.druid.stat.DruidStatService;
import com.alibaba.druid.support.http.stat.WebAppStatManager;

/**
 * @author limingwei
 */
public class SqlRequestUtil {
    public static String writeSqlRequestResponse(ApplicationContext applicationContext, String url) {
        Map<String, String> parameters = DruidStatService.getParameters(url);
        String sql = parameters.get("sql");

        if (null == sql) {
            return "SQL_IS_NULL";
        }

        DruidStatManagerFacade druidStatManager = DruidStatManagerFacade.getInstance();
        if (null == druidStatManager) {
            return "DRUID_STAT_MANAGER_FACADE_INSTANCE_IS_NULL";
        }

        List<Map<String, Object>> uriStatList = listBySql(sql);

        Map<String, Object> map = MapUtil.stringObjectMap("uriStatList", uriStatList, "sql", sql);
        String inputString = ResourceUtil.classPathResourceInputStreamToString(Constant.GRAPH_TEMPLATE_PATH + "/sql-request.htm");

        return FreemarkerUtil.freemarkerRender(inputString, map);
    }

    private static List<Map<String, Object>> listBySql(String sql) {
        List<Map<String, Object>> listBySql = new ArrayList<Map<String, Object>>();

        List<Map<String, Object>> uriStatList = WebAppStatManager.getInstance().getURIStatData();

        for (Map<String, Object> uriStat : uriStatList) {
            if (matchSql(uriStat, sql)) { // 包含匹配
                listBySql.add(uriStat);
            }
        }

        return listBySql;
    }

    private static boolean matchSql(Map<String, Object> uriStat, String sql) {
        List profiles = (List) uriStat.get("Profiles");

        for (Object profile : profiles) {
            Map profileMap = (Map) profile;
            Object profileType = profileMap.get("Type");
            if (!"SQL".equals(profileType)) {
                continue;
            }

            String profileName = (String) profileMap.get("Name");
            if (BudoGraphServiceUtil.SQL_2(sql).equalsIgnoreCase(BudoGraphServiceUtil.SQL_2(profileName))) {
                return true; // 这里去掉特殊字符再比较
            }
        }

        return false;
    }
}